package com.xiong.wuliao.HomeIntelligent;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.xiong.wuliao.R;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by asus on 2017/1/18.
 */
public class ChatMessageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    private List<ChatMessage> mData;

    public ChatMessageAdapter(Context context, List<ChatMessage> mData) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = mData;
    }


    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        ChatMessage chatMessage = mData.get(position);
        if (chatMessage.getType() == ChatMessage.Type.INCOMING){
            return 0;
        }
        return 1;
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ChatMessage chatMessage = mData.get(position);
        ViewHolder holder = null;
        if (convertView == null){
            // 通过Type设置不同的布局
            if (getItemViewType(position) == 0){
                convertView = mInflater.inflate(R.layout.item_from_msg,parent,false);
                holder = new ViewHolder();
                holder.mDate = (TextView) convertView.findViewById(R.id.id_from_msg_date);
                holder.mMsg = (TextView) convertView.findViewById(R.id.id_from_msg_info);
            }else {
                convertView = mInflater.inflate(R.layout.item_to_msg,parent,false);
                holder = new ViewHolder();
                holder.mDate = (TextView) convertView.findViewById(R.id.id_to_msg_date);
                holder.mMsg = (TextView) convertView.findViewById(R.id.id_to_msg_info);
            }
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        holder.mDate.setText(df.format(chatMessage.getDate()));
        holder.mMsg.setText(chatMessage.getMsg());

        return convertView;
    }

    private static class ViewHolder{
        TextView mDate; // 时间
        TextView mMsg; // 消息

    }
}
